package com.bidevalution.business.function;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.util.StringUtils;

import com.bidevalution.business.context.OpType;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;

public class FilterOfArrayFunction extends AbstractFunction{
	public FilterOfArrayFunction(FunctionInitializer functionInitializer) {
		super();
	}
	/**
	 * 返回数组中跟某个值进行比较的值范围
	 * <p>Description: </p>
	 * @param env
	 * @param arg1 数组
	 * @param arg2 比较符号 lt小于 lte小于等于 gt大于 gte大于或等于 eq等于
	 * @param arg3 比较值
	 * @return 返回例如:1,2,3,4
	 * @see com.googlecode.aviator.runtime.function.AbstractFunction#call(java.util.Map, com.googlecode.aviator.runtime.type.AviatorObject, com.googlecode.aviator.runtime.type.AviatorObject, com.googlecode.aviator.runtime.type.AviatorObject)
	 */
	@Override
	public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3) {
		String paramValue = FunctionUtils.getStringValue(arg1, env);
		List<String> tempList = new LinkedList<String>();
		List<String> priceList = new LinkedList<String>(Arrays.asList(paramValue.split(",")));
		String symbol = FunctionUtils.getStringValue(arg2, env);
		Double filterValue = Double.valueOf(arg3.getValue(env).toString());
		for(String price:priceList) {
			if(symbol.equals(OpType.lt.name())) {
				if(new BigDecimal(price).compareTo(new BigDecimal(filterValue))<0) {
					tempList.add(price);
				}
			}else if(symbol.equals(OpType.lte.name())) {
				if(new BigDecimal(price).compareTo(new BigDecimal(filterValue))<=0) {
					tempList.add(price);
				}
			}else if(symbol.equals(OpType.gt.name())) {
				if(new BigDecimal(price).compareTo(new BigDecimal(filterValue))>0) {
					tempList.add(price);
				}
			}else if(symbol.equals(OpType.gte.name())) {
				if(new BigDecimal(price).compareTo(new BigDecimal(filterValue))>=0) {
					tempList.add(price);
				}
			}else if(symbol.equals(OpType.eq.name())) {
				if(new BigDecimal(price).compareTo(new BigDecimal(filterValue))==0) {
					tempList.add(price);
				}
			}
			
		}
		return new AviatorString(StringUtils.collectionToDelimitedString(tempList, ","));
	}
	@Override
	public String getName() {
		return "filterOfArray";
	}

}
